package com.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.demo.dto.LoginFormDTO;
import com.demo.dto.PasswordLoginFormDTO;
import com.demo.dto.Result;
import com.demo.dto.UserDTO;
import com.demo.entity.User;
import com.demo.service.LoginService;
import com.demo.service.UserService;
import com.demo.utils.RedisConstants;
import com.demo.utils.RegexUtils;
import com.demo.utils.SystemConstants;
import com.demo.utils.VerifyCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.demo.utils.RedisConstants.LOGIN_TOKEN_PREFIX;
import static com.demo.utils.RedisConstants.LOGIN_TOKEN_TTL;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    UserService userService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<Void> verifyCode(String phoneNum) {
        if (RegexUtils.isPhoneInvalid(phoneNum)) {
            return Result.fail("手机号格式不正确");
        }

        // 符合，生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 将验证码保存到redis中 默认为2分钟
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phoneNum, code, RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        // 5.发送验证码
        log.debug("发送短信验证码成功，验证码：{}", code);

        return Result.ok();
    }

    @Override
    public Result<String> loginAndRegister(LoginFormDTO loginFormDTO) {
        // 1. 校验手机号
        String phone = loginFormDTO.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2. 不一致，返回
            return Result.fail("手机号格式错误");
        }
        // 3. 根据手机号查询验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        String code = loginFormDTO.getCode();
        if (cacheCode == null || !cacheCode.equals(code)) {
            return Result.fail("验证码错误");
        }

        // 4. 验证码通过，根据手机号查询用户
        User user = userService.query().eq("phone_num", phone).one();

        // 5. 判断用户是否存在，若不存在则创建用户
        if (user == null) {
            user = createUserWithPhone(loginFormDTO);
        }

        // 6.保存用户到redis中
        // 6.1.随机生成token，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        // 将user部分信息存储到redis中
        setUserInfoToRedis(user, token);

        // 7.返回token
        return Result.ok(token);
    }

    @Override
    public UserDTO setUserInfoToRedis(User user, String token) {
        // 6.2.将User对象转为HashMap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        // 6.3. 存储到redis中，key：token，value：userMap
        String tokenKey = LOGIN_TOKEN_PREFIX + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        // 设置token有效期 这里为30分钟
        stringRedisTemplate.expire(tokenKey, LOGIN_TOKEN_TTL, TimeUnit.MINUTES);
        return userDTO;
    }

    @Override
    public void imageCode(HttpServletResponse response, HttpSession session) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        String code = VerifyCodeUtil.drawImage(output);
        //将验证码文本直接存放到session中
        session.setAttribute("verifyCode", code);
        System.out.println(code);
        try {
            ServletOutputStream out = response.getOutputStream();
            output.writeTo(out);
            response.setHeader("Content-type", "image/png");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    boolean verifyCodeWrong(String sendCode, HttpSession session) {
        // 查看验证码是否正确
        String verifyCode = (String) session.getAttribute("verifyCode");
        return !StrUtil.equals(verifyCode, sendCode);
    }

    @Override
    public Result<String> loginByPassword(PasswordLoginFormDTO loginFormDTO, HttpSession session) {
        if (verifyCodeWrong(loginFormDTO.getCode(), session)) {
            //验证码错误，直接返回
            return Result.fail("验证码错误");
        }
        // 检验手机号和密码
        String phone = loginFormDTO.getPhone();
        String password = loginFormDTO.getPassword();
        User user = userService.query().eq("phone_num", phone).one();
        if (user == null) {
            return Result.fail("该手机号没有注册");
        }
        if (!StrUtil.equals(password, user.getPassword())) {
            return Result.fail("密码错误");
        }
        // 手机号密码正确，通过
        // 保存用户到redis中
        // 随机生成token，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        // 将user部分信息存储到redis中
        setUserInfoToRedis(user, token);

        // 返回token
        return Result.ok(token, "登录成功");
    }

    @Override
    public Result<String> registerByPassword(PasswordLoginFormDTO loginFormDTO, HttpSession session) {
        if (verifyCodeWrong(loginFormDTO.getCode(), session)) {
            //验证码错误，直接返回
            return Result.fail("验证码错误");
        }
        String phone = loginFormDTO.getPhone();
        String password = loginFormDTO.getPassword();
        User user = userService.query().eq("phone_num", phone).one();
        if (user != null) {
            // 手机号已注册，返回
            return Result.fail("手机号已注册");
        }
        User newUser = createUserWithPassword(loginFormDTO);
        return Result.ok("注册成功");
    }

    private User createUserWithPhone(LoginFormDTO loginFormDTO) {
        User user = new User();
        user.setPhoneNum(loginFormDTO.getPhone());
        user.setNickname(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        // 设置头像默认值
        user.setAvatar(SystemConstants.DEFAULT_AVATAR_URL);
        userService.save(user);
        return user;
    }

    private User createUserWithPassword(PasswordLoginFormDTO loginFormDTO) {
        User user = new User();
        user.setPhoneNum(loginFormDTO.getPhone());
        user.setPassword(loginFormDTO.getPassword());
        user.setNickname(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        // 设置头像默认值
        user.setAvatar(SystemConstants.DEFAULT_AVATAR_URL);
        userService.save(user);
        return user;
    }
}
